<template>
<thead>
  <tr>
    <th v-if="hasCheckbox" class="checkbox-column">
      <label class="et-checkbox">
        <input type="checkbox" v-model="chooseAll" />
        <span></span>
      </label>
    </th>
    <th v-for="(header, idx) in headers" :key="idx" :style="{'min-width': `${header.minWidth}rem`}">
      <table-filter ref="filter"
                    v-if="header.type === 'filter'"
                    :id="header.id"
                    :txt="header.txt"
                    :icon="header.icon"
                    :type="header.isRadio ? 'radio' : 'checkbox'"
                    :items="header.items"
                    :width="header.width"
                    @tableFilter="filterHandler" />
      <a v-if="header.type === 'link'" @click="header.handler">
        {{ header.txt }}
        <et-icon v-if="header.icon" :name="header.icon" />
      </a>
      <template v-if="header.type === 'txt'">
        {{ header.txt }}
      </template>
    </th>
    <th v-if="hasFilter" style="width: 1rem">
      <a @click="clearFilter">
        <et-icon :name="clearIcon" />
      </a>
    </th>
  </tr>
</thead>
</template>

<script>
import { EtIcon } from '../../widgets';
import TableFilter from './TableFilter';

export default {

  components: {
    EtIcon,
    TableFilter
  },

  props: {
    headers: {
      type: Array,
      requried: true
    },
    filters: {
      type: Object,
      default() { return {}; }
    },
    hasCheckbox: {
      type: Boolean
    },
    chooseAllHandler: {
      type: Function,
      default: () => {}
    },
    clearIcon: {
      type: String,
      default: 'close'
    },
    chooseItems: {
      type: Array,
      default: () => []
    },
    rowNum: {
      type: Number,
      required: true
    },
    filterHandler: {
      type: Function,
      default: () => {}
    },
    clearFilterHandler: {
      type: Function,
      default: () => {}
    }
  },

  data() {
    return {
      hasFilter: Object.keys(this.filters).length === 0 ? false : true
    };
  },

  computed: {
    chooseAll: {
      get() {
        return this.chooseItems.length === this.rowNum && this.rowNum > 0;
      },
      set(val) {
        this.chooseAllHandler(val);
      }
    }
  },

  watch: {
    filters: {
      handler(val) {
        this.hasFilter = Object.keys(this.filters).length === 0 ? false : true;
      },
      deep: true
    }
  },

  methods: {
    clearFilter() {
      this.$refs.filter.map((f) => {
        f.clear();
      });
      this.clearFilterHandler();
    }
  }

};
</script>
